package com.alfy.sbdemo.websocketdemo.demo2;

import org.springframework.http.HttpStatus;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

// 拦截器实现
@Component
public class MyAuthHandshakeInterceptor extends HttpSessionHandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        // 从请求中获取认证信息
        HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
        String authHeader = servletRequest.getHeader("Authorization");
        // 进行认证检查
        if (validateToken(authHeader)) {
            System.out.println("Authorization pass");
            return true; // 认证通过
        }
        // 认证失败换种方式
        String token = servletRequest.getParameter("token");
        if (validateToken(token)) {
            System.out.println("Authorization pass");
            return true; // 认证通过
        }
        System.out.println("Authorization error");
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return false; // 认证失败
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {
        // 可以进行一些后续处理
        super.afterHandshake(request, response, wsHandler, ex);
    }

    private boolean validateToken(String authHeader) {
        // 在这里进行 token 的验证逻辑
        return "valid-token".equals(authHeader); // 示例代码，实际应用中替换为实际验证逻辑
    }

}
